/*
Recorte de poligonos.
Use r para recortar el polígono y mostrar el resultado final
Use n para reiniciar el dibujo
*/

color backgroundColor = color(255, 255, 255);
int w = 800;
int h = 600;
Polygon window;
int WINDOW_SIZE = 100;
boolean first = true;
boolean end = false;
Polygon pol;
color bgColor = color(random(255), random(255), random(255));
color fgColor = color(0);
int x0, y0;
int initX, initY;
Action activeAction = null;
PGraphics pg;
boolean cutted = false;
Polygon newPolygon;

void setup() {
    size(w, h);
    background(backgroundColor); 
    pg = createGraphics(w, h);
}


void draw() {
  pg.beginDraw();
  pg.background(backgroundColor);
  if(!first) {
    pol.draw(pg,false);
    pg.stroke(0);
    pg.line(x0, y0, mouseX, mouseY);
  }
  if(window!=null && !cutted) {
     //pol.fill(pg,bgColor);
     window.draw(pg);
     pol.draw(pg);
  }
  if(cutted) {
     pg.background(backgroundColor);
     newPolygon.draw(pg);
     newPolygon.fill(pg,color(random(255), random(255), random(255)));
  }
  
  pg.endDraw();
  image(pg, 0,0);
}

void mouseClicked() {
  if (activeAction!=null) {
        activeAction.mouseClick(mouseX,mouseY);
  }
  if (first && !end) {
    pg.background(backgroundColor);
    first = false;
    x0 = mouseX;
    y0 = mouseY;
    pol = new Polygon(bgColor,fgColor);
    pol.addPoint(new PVector(x0, y0));
  }
  else {
    if(!end) {
      x0 = mouseX;
      y0 = mouseY;
      pol.addPoint(new PVector(x0, y0));
      if (mouseButton == RIGHT) {
        pol.draw(pg);
        first = true;
        end = true;
        drawWindow();
      }
    }
  }
}

void mouseDragged() {
  stroke(0);
  if(end) {
     if (activeAction!=null) {
        activeAction.mouseDrag(mouseX, mouseY);
     }
  }  
}

void keyPressed() {
  if (key == 'R' || key == 'r') {
    if(window != null) {
      pg.background(backgroundColor);
      newPolygon = pol.cutPolygon(window);
      cutted = true;     
    }
  } 
  if (key == 'N' || key == 'n') {
    pg.background(backgroundColor);
    pol = null;
    window = null;
    first = true;
    end = false;
    cutted = false;
    Action activeAction = null;
  } 
}


void drawWindow() {
  window = new Polygon();
  window.addPoint(0,0);
  window.addPoint(0,WINDOW_SIZE);
  window.addPoint(WINDOW_SIZE,WINDOW_SIZE);
  window.addPoint(WINDOW_SIZE,0);
  window.draw(pg);
  activeAction = new TranslatePolygon(window);
}
